import React, { memo ,useEffect,shallowequal,useRef,useState,useCallback} from 'react'
import {useDispatch,useSelector} from 'react-redux'
import {getCurrentSongAction,
        ChangeCycleIndexAction,
        ChangeSong,
        changeCurrentLyricIndex,
        changeIsShowPannel,
        } from '../store/actionCreators'
import { NavLink } from 'react-router-dom';
import { Slider ,message} from 'antd';
import {getSizeImage,formatMinuteSecond,getPlayUrl} from 'utils/format-utils'
import {
  PlaybarWrapper,
  Control,
  PlayInfo,
  Operator
} from './style';
import HNPlayerBannel from '../../player/app-player-bannel'

export default memo(function HNPlayerBar() {

  const [currentTime,setCurrentTime] = useState(0);
  const [duration,setDuration] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isChanging, setIsChanging] = useState(false);
  const [totalTime, setTotalTime] = useState(0);
  

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getCurrentSongAction(167876));
  },[dispatch])


  const {currentSong,
         playList,
         cycleIndex,
         lyric,
         currentLyricIndex,
         isShowPannel,
         isShowMessage
        } 
    = useSelector(state => ({
    currentSong : state.getIn(["player", "currentSong"]),
    playList : state.getIn(["player", "playList"]),
    cycleIndex : state.getIn(["player", "cycleIndex"]),
    lyric : state.getIn(["player", "lyric"]),
    currentLyricIndex:state.getIn(["player", "currentLyricIndex"]),
    isShowPannel : state.getIn(["player", "isShowPannel"]),
    isShowMessage : state.getIn(["player", "isShowMessage"])
  }),shallowequal)

  const audioRef = useRef();

  const picUrl = (currentSong.al && currentSong.al.picUrl) || "";
  const SingleName = (currentSong.ar && currentSong.ar[0].name) || "未知歌手";
  const showCurrentTime = formatMinuteSecond(currentTime);

  useEffect(()=>{
    audioRef.current.src = getPlayUrl(currentSong.id);
    setTotalTime(currentSong.dt);
    /* audioRef.current.play().then(res=>{
      setIsPlaying(true);
    }).catch(err => {
      setIsPlaying(false);
    });  */
  },[currentSong])

  const plyaMusic = useCallback(()=>{
    setIsPlaying(!isPlaying);
    isPlaying ? audioRef.current.pause() : audioRef.current.play();
  },[isPlaying])

  const timeUpdate = e =>{
    if(!isChanging){
      setCurrentTime(e.target.currentTime * 1000);
      setDuration((e.target.currentTime * 1000) / totalTime * 100);
    }
  
    let i = 0;
   /*  console.log(currentTime,lyric[0].time); */
    if(lyric.length !== 0){
      for(;i<lyric.length;++i){
        if(currentTime < lyric[i].time){
          break;
        }
      }
      const preLyricIndex = i-1;
      if(currentLyricIndex !== preLyricIndex){
        dispatch(changeCurrentLyricIndex(preLyricIndex));
        message.open({
          content: lyric[preLyricIndex] ? lyric[preLyricIndex].content:'',
          key: "Lyrics",
          duration: 0,
          className: 'lyric-message',
        })
      }
    }
  }

  const timeEnd = ()=>{
    if(cycleIndex === 2 || playList.length === 1 || playList.length === 0){
      audioRef.current.time = 0;
      audioRef.current.play();
    }else{
     dispatch(ChangeSong(1));
    }
  }

  const sliderChange = useCallback(value => {
    setDuration(value);
    setCurrentTime(value / 100 * totalTime );
    setIsChanging(true);
  },[totalTime])

  const sliderAfterChange = useCallback(value => {
    const time = value / 100.0 * totalTime /1000;
    audioRef.current.currentTime = time;
    setIsChanging(false);
    if (!isPlaying) {
      plyaMusic();
    }
  },[totalTime,isPlaying,plyaMusic])

  const handleCycle = ()=>{
    dispatch(ChangeCycleIndexAction(cycleIndex+1));
  }

  const prevAndNextHandle = (num) => {
    if(playList.length === 0){
      return;
    }
    dispatch(ChangeSong(num));
  }
  

  return (
     <PlaybarWrapper className="sprite_playbar">
      <div className="content wrap-v2" >
        <Control isPlaying = {isPlaying}>
          <button className="sprite_playbar btn prev" onClick={e=>prevAndNextHandle(-1)}></button>
          <button className="sprite_playbar btn play"
          onClick={e=>{plyaMusic()}}></button>
          <button className="sprite_playbar btn next" onClick={e=>prevAndNextHandle(1)}></button>
        </Control>
        <PlayInfo>
          <div className="image">
            <NavLink to="/discover/player">
              <img src={getSizeImage(picUrl, 34)} alt="" />
            </NavLink>
          </div>
          <div className="info">
            <div className="song">
              <span className="song-name">{currentSong.name}</span>
              <span className="singer-name">{SingleName}</span>
            </div>
            <div className="progress">
              <Slider value={duration} onChange={sliderChange} onAfterChange={sliderAfterChange}/>
              <div className="time">
                <span className="now-time">{showCurrentTime}</span>
                <span className="divider">/</span>
                <span className="total-time">{formatMinuteSecond(currentSong.dt)}</span>
              </div>
            </div>
          </div>
        </PlayInfo>
        <Operator sequence={cycleIndex}>
          <div className="left">
            <button className="sprite_playbar btn favor"></button>
            <button className="sprite_playbar btn share"></button>
          </div>
          <div className="right sprite_playbar">
            <button className="sprite_playbar btn volume"></button>
            <button className="sprite_playbar btn loop" onClick={e=>handleCycle()}></button>
            <button className="sprite_playbar btn playlist" onClick={e=>dispatch(changeIsShowPannel(!isShowPannel))}>
              {playList.length}
              {
                isShowMessage && <span className="add_song_message sprite_playbar">已添加到播放列表</span>
              }
            </button>
          </div>
        </Operator>
      </div>
      <audio ref={audioRef} onTimeUpdate={timeUpdate} onEnded={timeEnd}/>
     { isShowPannel? <HNPlayerBannel/> : ""}
    </PlaybarWrapper>
  )
})
